package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SmsService smsService;//发送短信的服务
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;


    @Override
    public void getCode(String phone) {
        //验证手机号是否为空
        if(!StringUtils.hasText(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //验证码的key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;

        //判断redis中是否已经包含手机号的key
        if(redisTemplate.hasKey(key)){
            //如果包含，则判断是否在60秒内发送过短信

            //获取验证码还有多长时间过期
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);

            //获取验证码已过期时间
            Long expiredTime = RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire;

            if(expiredTime<RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }

        }

        //发送随机的6位验证码
        String code = VerifyCodeUtil.generateVerifyCode(6);
        smsService.sendSms(phone, code);

        //将验证码保存到redis中，并设置过期时间
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }

    @Override
    public String login(LoginVo loginVo) {
        //判断手机号是否为空
        String phone = loginVo.getPhone();
        if(!StringUtils.hasText(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        //判断验证码是否为空
        String code = loginVo.getCode();
        if(!StringUtils.hasText(code)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //验证码的key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        //获取redis中保存的验证码
        String redisCode = redisTemplate.opsForValue().get(key);
        if(redisCode==null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if(!code.equals(redisCode)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //判断phone的用户是否已注册为会员
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        if(userInfo==null){
            //会员不存在，直接注册为会员
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-"+phone.substring(5));
            userInfoMapper.insert(userInfo);
        }
        //若存在，判断账号是否被禁用
        if(userInfo.getStatus()==BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        //登录成功，生成token
        String token = JwtUtil.createToken(phone, userInfo.getId());

        return token;
    }
}
